/**
 * 
 */
package game.kill.task;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author macbook
 *
 */
public class GameProcessTask {

	private static final Logger logger = LoggerFactory.getLogger(GameProcessTask.class);
	
	private ScheduledExecutorService scheduledExecutorService;
	
	private int poolSize = 2;
	
	private boolean daemon = Boolean.TRUE;
	
	private Map<Integer,ScheduledFuture<?>> futureMap = new HashMap<Integer, ScheduledFuture<?>>();
	
	/**
	 * 初始化 scheduledExecutorService
	 */
	private void initScheduledExecutorService(){
		logger.info("daemon:{},poolSize:{}",daemon,poolSize);
		scheduledExecutorService =  Executors.newScheduledThreadPool(poolSize,new ThreadFactory() {

			@Override
			public Thread newThread(Runnable arg0) {
				Thread thread = Executors.defaultThreadFactory().newThread(arg0);
				//设置守护线程
				thread.setDaemon(daemon);
				return thread;
			}
		});
	}
	
	public void addGameSchedule(final Integer roomId,int initialDelay,int delay){
		if(scheduledExecutorService == null){
			initScheduledExecutorService();
		}
		if(futureMap.containsKey(roomId)){
			futureMap.get(roomId).cancel(true);
		}
		ScheduledFuture<?> scheduledFuture =  scheduledExecutorService.schedule(new Runnable() {
			@Override
			public void run() {
				
				logger.info("TICKET refurbish with roomId:{}",roomId);
			}
		},delay,TimeUnit.SECONDS);
		futureMap.put(roomId,scheduledFuture);
	}
	
	public static void main(String[] args) {
		GameProcessTask task = new GameProcessTask();
		
		for(int i=1;i<=10;i++){
			task.addGameSchedule(i, 0, i);
		}
		
		while(task.scheduledExecutorService != null){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
